package com.example.testnetty.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.testnetty.R;
import com.example.testnetty.eventbus.MainMsg;
import com.example.testnetty.netty.NettyManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity {

    private final String TAG = MainActivity.class.getSimpleName();
    private Button btn_send;
    private TextView tvText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        intiView();
    }

    private void intiView() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                NettyManager.getInstance().connectNetty();
            }
        },1000);
        btn_send = findViewById(R.id.btn_send);
        tvText = findViewById(R.id.tv_text);
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NettyManager.getInstance().sendData("Hello,My name is clint！");
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsg(MainMsg mainMsg) {
        String tvData = tvText.getText().toString();
        if(TextUtils.isEmpty(tvData)){
            tvText.setText(mainMsg.msg);
        }else {
            tvData = tvData + "\n" + mainMsg.msg;
            tvText.setText(tvData);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}